﻿using System;
using System.IO;
using System.Net;
using Common.Utils;
using Newtonsoft.Json;

namespace Common.Client
{
    public static class HttpClient
    {
        public static HttpGetResponse Get(Uri uri)
        {
            return new HttpGetResponse(uri);
        }

        public class HttpGetResponse
        {
            private readonly Uri requestUri;

            public HttpGetResponse(Uri uri)
            {
                requestUri = uri;
            }

            public string AsString()
            {
                string output = String.Empty;

                WebResponse response = WebRequest.Create(requestUri).GetResponse();
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    output = reader.ReadToEnd();
                    reader.Close();
                }
                response.Close();

                return output;
            }

            public T As<T>() where T : class
            {
                T output = null;

                using (var stringReader = new StringReader(AsString()))
                {
                    var jsonReader = new JsonTextReader(stringReader);
                    var serializer = new JsonSerializer();
                    serializer.Converters.Add(new JsonEnumTypeConverterExtensions.JsonEnumTypeConverter());
                    output = serializer.Deserialize<T>(jsonReader);
                }

                return output;
            }
        }
    }
}
